$(document).ready(function(){
    $(".productBuy").click(function() {
        var add = $(this);
        var pic = $(this).siblings(".productPhoto");
        var pos = $("#cart").position();
        var img = pic.find("img");
        var id = $(this).siblings(".productWrapper").find(".productId").val();
        var quantityInput = $(this).siblings(".productWrapper").find(".productQuantity");
        var quantity = new Number(quantityInput.val());
        if(quantity.isNaN || quantity.toString() == "NaN" || quantity < 0)
            quantity = new Number(0);
        quantity = quantity.toFixed(0);
        if(quantity == 0) {
            quantityInput.val("");
            return;
        } 
        var jsonString = '{ "hash" : {';
        jsonString += '"' + id + '" : "' + quantity + '"}}';
        var data = $.parseJSON(jsonString);
        $.post("/cart/add",
            data,
            function(dataReceive){
                add.css("visibility", "hidden");
                img.css({
                    "left" : img.position().left,
                    "top" : img.position().top,
                    "position" : "absolute"
                });
                img.animate({
                    "left" : pos.left,
                    "top" : pos.top,
                    "opacity" : 0
                },1000,function() {
                    img.hide();
                    img.css({
                        "position" : "static",
                        "left" : "auto",
                        "top" : "auto",
                        "opacity" : 1
                    });
                    quantityInput.val("");
                    $(".cartTotalQuantityValue").text(dataReceive["quantity"]);
                    $(".cartTotalPriceValue").text(dataReceive["price"].toFixed(2));
                    img.fadeIn();
                    add.css("visibility", "visible");
                });
            },"json"
            );
    });
});